import dayjs from 'dayjs'

// 给定范围的天或年后的日期 d y
export const rangeDayOrYearToDate = (
  n = 20,
  unit: 'y' | 'd' = 'y'
): [string, dayjs.Dayjs] => {
  // 将字符串转换成 Day.js 对象
  const dateObj = dayjs(Date.now())
  // 在当前时间上加上n天或年
  let newDateObj = dateObj.add(n, unit)
  return [newDateObj.format('YYYY-MM-DD'), newDateObj]
}

// 读取本地文件
// 1 readAsArrayBuffer
// 2 readAsBinaryString
// 3 readAsDataURL :Promise<ArrayBuffer>
export const readerFile = (
  file: Blob,
  type: 1 | 2 | 3 = 1
): Promise<string | ArrayBuffer | null | undefined> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    if (type == 1) {
      reader.readAsArrayBuffer(file)
    } else if (type == 2) {
      reader.readAsBinaryString(file)
    } else if (type == 3) {
      reader.readAsDataURL(file)
    }
    reader.onload = ({ target }) => {
      resolve(target?.result)
    }
    reader.onerror = (err) => {
      reject(err)
    }
  })
}

// 把一个json转换为search字符串
export const jsonToSearch = (json: Record<string, any>): string => {
  let search = ''
  for (let key in json) {
    search += `&${key}=${json[key]}`
  }
  return search
}


export const delay = (ms = 3000) => {
  return new Promise((_) => {
    setTimeout(() => {
      _('')
    }, ms)
  })
}